{% extends "base.html" %}

{% block title %}日志{% endblock %}

{% block head %}
{{ super() }}
<link rel="stylesheet" href="/static/xterm/3.14.5/xterm.css"/>

{% endblock %}


{% block content %}
<!-- 页面头 -->
<!--<section class="content-header">-->
<!--  &lt;!&ndash;头部标题&ndash;&gt;-->
<!--  <h1>-->
<!--    执行命令行-->
<!--    &lt;!&ndash;    <small>advanced tables</small>&ndash;&gt;-->
<!--  </h1>-->
<!--  &lt;!&ndash;面包屑&ndash;&gt;-->
<!--  <ol class="breadcrumb">-->
<!--    <li><a href="/"><i class="fa fa-home"></i> 主页</a></li>-->
<!--    <li><a href="/cluster">集群管理</a></li>-->
<!--    <li>工作负载</li>-->
<!--    <li>详情</li>-->
<!--    <li class="active">命令行</li>-->
<!--  </ol>-->
<!--</section>-->

<!-- 页面内容 -->
<section class="content">
  <div class="row">
    <div class="col-xs-12">
      <div>
        <p>
          <span><b>命令行</b></span>&nbsp;&nbsp;
          集群: <span>{{cluster_name}}</span>&nbsp;&nbsp;&nbsp;
          命名空间: <span id="namespace"></span>&nbsp;&nbsp;&nbsp;
          Pod: <span id="pod"></span>&nbsp;&nbsp;&nbsp;
          容器: <span id="container"></span>&nbsp;&nbsp;
          <button type="button" id="downloadBtn">操作日志</button>
          <button type="button" id="clearBtn">清屏</button>
          <button type="button" id="downloadFileBtn">下载文件</button>
          <!--          <button type="button" id="bottomBtn">跳到底部</button>-->
        </p>
      </div>

      <div id="terminal"></div>

    </div>
    <!-- /.col -->
  </div>
  <!-- /.row -->
</section>
<!-- /.页面内容 -->
{% endblock %}


{% block script %}

<script type="text/javascript" src="/static/xterm/3.14.5/xterm.js"></script>
<script type="text/javascript" src="/static/xterm/3.14.5/fit.js"></script>
<script type="text/javascript">
    // 定义全局变量,用于下载
    var download_txt = ""

    // 下载日志的函数
    function download(filename, text) {
        var element = document.createElement('a');
        element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
        element.setAttribute('download', filename);
        element.style.display = 'none';
        document.body.appendChild(element);
        element.click();
        document.body.removeChild(element);
    }

    // 页面载入后执行
    $(function () {
        // 心跳总开关
        var ping_switch = true
        // 初始化xterm
        var term = new Terminal({
            fontSize: 15,
            fontFamily: 'courier',
            disableStdin: false,
            cursorBlink: true, // 光标闪烁
            cursorStyle: "block", // 光标样式 'block' | 'underline' | 'bar'
            scrollback: 10000, // 当行的滚动超过初始值时保留的行视窗，越大回滚能看的内容越多，
        });
        term.open(document.getElementById('terminal'));

        // xterm 窗口自适应
        Terminal.applyAddon(fit);
        // 载入后 以及每次调整窗口大小后，同时调整日志消息框的大小
        $('#terminal').css('height', $(window).height() - 100)
        term.fit();
        $(window).resize(function () {
            $('#terminal').css('height', $(window).height() - 100)
            term.fit();
        })


        // 解析URL，获取参数，连接websocket服务器
        var pathName = window.document.location.pathname;
        var pathList = pathName.split("/")        // 例如 /cluster/ 被解析为 ['', 'cluster', '']
        console.log(pathList)
        var clusterid = pathList[3]
        var namespace = pathList[4]
        var pod = pathList[5]
        var container = pathList[6]
        console.log(clusterid, namespace, pod, container)
        if (clusterid == false || namespace == false || pod == false || container == false) {
            alert("无法获取到容器，请联系管理员")
            return
        }
        $('#namespace').text(namespace)
        $('#pod').text(pod)
        $('#container').text(container)


        term.write("connecting to pod " + pod + "...")
        term.on('data', function (data) {
            msg = {operation: "stdin", data: data}
            conn.send(JSON.stringify(msg))
        });
        // term.on('resize', function (size) {
        //     console.log("resize: " + size)
        //     msg = {operation: "resize", cols: size.cols, rows: rows}
        //     conn.send(JSON.stringify(msg))
        // });

        url = "ws://" + document.location.host + "/ws/" + clusterid + "/" + namespace + "/" + pod + "/" + container + "/webshell"
        console.log(url);
        conn = new WebSocket(url);


        conn.onopen = function (e) {
            term.write("\r");
            msg = {operation: "stdin", data: "export TERM=xterm && clear \r"}
            conn.send(JSON.stringify(msg))
            // term.clear()

            // 保持心跳
            let a = 1;

            function ping() {
                // 如果总开关关闭，或者计数器大于60（半个小时）则关闭心跳
                if (!ping_switch || a > 60) return;
                console.log("发送心跳：", a++)
                msg = {operation: "ping"}
                conn.send(JSON.stringify(msg))
                setTimeout(ping, 30000); // 每30秒发送心跳一次
            }

            ping();
        };

        conn.onmessage = function (event) {
            msg = JSON.parse(event.data)
            if (msg.operation === "stdout") {
                term.write(msg.data)
            } else {
                console.log("invalid msg operation: " + msg)
            }
            download_txt += msg.data
        };

        conn.onclose = function (event) {
            if (event.wasClean) {
                console.log(`[close] Connection closed cleanly, code=${event.code} reason=${event.reason}`);
            } else {
                console.log('[close] Connection died');
                term.writeln("")
            }
            term.write('Connection Reset By Peer! Try Refresh.');
            ping_switch = false;
        };

        conn.onerror = function (error) {
            console.log('[error] Connection error');
            term.write("error: " + error.message);
            term.destroy();
            ping_switch = false;
        };

        // 下载按钮
        $("#downloadBtn").click(function (event) {
            download("opration_log.txt", download_txt);
        });

        // 清除按钮
        $("#clearBtn").click(function (event) {
            term.clear();
        });

        // 滚到底部按钮
        $("#bottomBtn").click(function (event) {
            term.scrollToBottom();
        });


        $('#downloadFileBtn').click(function () {
            // http://127.0.0.1:{{ws_port}}/copy/100/default/nginx-deployment-8d8d4dc86-sqfcx/nginx/download\?file\=/root/sss
            bootbox.prompt({
                size: "large",
                title: "输入下载文件的绝对路径（例如 /var/log/nginx/error.log）",
                value: "",
                callback: function (result) {
                    /* result = String containing user input if OK clicked or null if Cancel clicked */
                    if (result) {
                        url = "http://" + document.location.host + "/copy/" + clusterid + "/" + namespace + "/" + pod + "/" + container + "/download?file=" + result.trim()
                        // $.get(url, function (data) {
                        //     console.log(data)
                        // })
                        window.location = url
                    }
                }
            });
        })

    });
</script>
{% endblock %}